package com.sandu.lib_common.webview

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.R
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.sandu.lib_common.base.BaseVBActivity
import com.sandu.lib_common.databinding.ActivityWebBinding
import com.sandu.lib_common.view.SmartRefreshWebLayout

/**
 * 作者　: sandu
 * 时间　: 2024/11/21
 * 描述　: 子类web会报错，需要处理 todo
 */
open class BaseWebActivity : BaseVBActivity<BaseWebActivityViewModel, ActivityWebBinding>() {
    private var mAlertDialog: AlertDialog? = null
    private var mAgentWeb: AgentWeb? = null
    lateinit var smartRefreshWebLayout: SmartRefreshWebLayout
    override fun initView(savedInstanceState: Bundle?) {
        this.setSupportActionBar(mViewBind.toolbar)
        if (supportActionBar != null) {
            // Enable the Up button
            supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        }
        mViewBind.toolbar.setNavigationOnClickListener(View.OnClickListener { showDialog() })


        val p = System.currentTimeMillis()
        smartRefreshWebLayout = SmartRefreshWebLayout(this)

        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(mViewBind.container, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebChromeClient(mWebChromeClient)
            .setWebViewClient(mWebViewClient)
            .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
            .setWebLayout(smartRefreshWebLayout)
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
            .interceptUnkownUrl() //拦截找不到相关页面的Scheme
            .createAgentWeb()
            .ready()
            .go(getUrl())

        if (mAgentWeb != null) {
            //注入对象
            mAgentWeb!!.jsInterfaceHolder.addJavaObject(
                "android",
                AndroidInterface(mAgentWeb!!, this@BaseWebActivity)
            )
        }


        //mAgentWeb.getUrlLoader().loadUrl(getUrl());
        val n = System.currentTimeMillis()
        Log.i("Info", "init used time:" + (n - p))
    }

    private fun showDialog() {
        if (mAlertDialog == null) {
            mAlertDialog = AlertDialog.Builder(this)
                .setMessage("您确定要关闭该页面吗?")
                .setNegativeButton("再逛逛") { dialog, which ->
                    if (mAlertDialog != null) {
                        mAlertDialog!!.dismiss()
                    }
                } //
                .setPositiveButton("确定") { dialog, which ->
                    if (mAlertDialog != null) {
                        mAlertDialog!!.dismiss()
                    }
                    this@BaseWebActivity.finish()
                }.create()
        }
        mAlertDialog!!.show()
    }

    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted")
            smartRefreshWebLayout.getmSmartRefreshLayout().finishRefresh()
        }

        override fun onPageFinished(webView: WebView, s: String) {
            super.onPageFinished(webView, s)
            Log.i("Info", "BaseWebActivity onPageFinished")
        }
    }
    private val mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView, title: String) {
            super.onReceivedTitle(view, title)
            if (mViewBind.toolbarTitle != null) {
                mViewBind.toolbarTitle.setText(title)
            }
        }
    }

    open fun getUrl(): String {
        return "https://baidu.com"
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (mAgentWeb!!.handleKeyEvent(keyCode, event)) {
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onPause() {
        mAgentWeb!!.webLifeCycle.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb!!.webLifeCycle.onResume()
        super.onResume()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.i("Info", "onResult:$requestCode onResult:$resultCode")
        super.onActivityResult(requestCode, resultCode, data)
    }


    override fun onDestroy() {
        super.onDestroy()
        //mAgentWeb.destroy();
        mAgentWeb!!.webLifeCycle.onDestroy()
    }
}